package com.wholeintech.wirednet;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.wholeintech.dao.DeviceDao;
import com.wholeintech.dao.NavigationDao;
import com.wholeintech.entity.Navigation;
import com.wholeintech.entity.ReciveDeviceInfo;
import com.wholeintech.zigbee.gw.DeviceManager;
import com.wholeintech.utils.CommonUtil;
import com.wholeintech.entity.DeviceDb;
import com.wholeintech.zigbee.util.DeviceDbManager;
import com.wholeintech.zigbee.util.PollTheadTemp;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.wholeintech.utils.CommonIntent.ACTION_BOX_WIREDNET_IN;
import static com.wholeintech.utils.CommonIntent.ACTION_CTL_AIRCONDITION;
import static com.wholeintech.utils.CommonIntent.ACTION_CTL_CURTAIN;
import static com.wholeintech.utils.CommonIntent.ACTION_CTL_FLOOR_HEATING;
import static com.wholeintech.utils.CommonIntent.ACTION_CTL_FRESHAIR;
import static com.wholeintech.utils.CommonIntent.ACTION_CTL_LIGHT;
import static com.wholeintech.utils.CommonIntent.ACTION_CTL_LIGHT_8;
import static com.wholeintech.utils.CommonIntent.ACTION_CTL_SWITCH;
import static com.wholeintech.utils.CommonIntent.ACTION_CTL_TRANSDATA;
import static com.wholeintech.utils.CommonIntent.ACTION_DEV_ADD;
import static com.wholeintech.utils.CommonIntent.ACTION_DEV_BIND;
import static com.wholeintech.utils.CommonIntent.ACTION_DEV_CLEARLIST;
import static com.wholeintech.utils.CommonIntent.ACTION_DEV_CTL_BY_WIRED_NET;
import static com.wholeintech.utils.CommonIntent.ACTION_DEV_DEVCHANAGE;
import static com.wholeintech.utils.CommonIntent.ACTION_DEV_MANAGER;
import static com.wholeintech.utils.CommonIntent.ACTION_DEV_ONOFFLINE;
import static com.wholeintech.utils.CommonIntent.ACTION_DEV_REMOVE;
import static com.wholeintech.utils.CommonIntent.ACTION_DEV_SECURITYKEY;
import static com.wholeintech.utils.CommonIntent.ACTION_DEV_STATUS;
import static com.wholeintech.utils.CommonIntent.ACTION_HCP_RESET;
import static com.wholeintech.utils.CommonIntent.ACTION_HCP_UPDATED;
import static com.wholeintech.utils.CommonIntent.ACTION_INFO_RETURN;
import static com.wholeintech.utils.CommonIntent.ACTION_SENCE_ADD;
import static com.wholeintech.utils.CommonIntent.ACTION_SENCE_DEV_ADD;
import static com.wholeintech.utils.Constants.Dev_STATUS_eDisconnect;

/**
 * 有线网服务
 */
public class WiredNetService extends Service {
    private final static String TAG = "WireNetService";
    private final static boolean debug = true;
    private final static int WIRDNET_RESPONSE = 1;

    public Context mContext;
    long timestamp = 0;

    private DeviceDbManager mDeviceDbManager;
    private WrdNetDeviceControl WrdNetDeContol;
    private ArrayList<ReciveDeviceInfo> deviceList;

    PollTheadTemp netHandlethread;            //Add by hy,2018/03/27
    ExecutorService singleThreadExecutorReceive;

    public WiredNetService() {
    }

    private final Handler responseHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WIRDNET_RESPONSE:
                    Intent intent = (Intent) msg.obj;
                    intentRsp(intent.getAction(), msg.arg1);
                    break;
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();

        mContext = this;

        Log.d(TAG, "WireNet Service Start");
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ACTION_DEV_ADD);
        mFilter.addAction(ACTION_DEV_REMOVE);
        mFilter.addAction(ACTION_DEV_ONOFFLINE);
        mFilter.addAction(ACTION_DEV_CLEARLIST);
        mFilter.addAction(ACTION_DEV_BIND);
        mFilter.addAction(ACTION_DEV_SECURITYKEY);
        mFilter.addAction(ACTION_DEV_STATUS);        //Add by hy,2018/03/23

        //统一使用下面的广播,由zigbeeservice 统一转发而来
        mFilter.addAction(ACTION_DEV_CTL_BY_WIRED_NET);

        mFilter.addAction(ACTION_SENCE_ADD);
        mFilter.addAction(ACTION_SENCE_DEV_ADD);
        mFilter.addAction(ACTION_HCP_RESET);
        mFilter.addAction(ACTION_HCP_UPDATED);                    //Add by hy,2018/03/29
        mFilter.addAction(ACTION_BOX_WIREDNET_IN);                //Add by hy,2017/03/23
        mFilter.addAction(ACTION_CTL_TRANSDATA);                //Add by hy,2017/06/20

        registerReceiver(mReceiver, mFilter);

        mDeviceDbManager = DeviceDbManager.getInstance(mContext);
        WrdNetDeContol = WrdNetDeviceControl.getInstance(responseHandler, mContext);
        WrdNetDeviceManager WrdNetDeviceManger = new WrdNetDeviceManager(mContext);
        deviceList = WrdNetDeviceManger.getDeviceList();

        new Thread(WrdNetDeviceManger).start();     //
        //Add by hy,2017/09/06，Wirenet FB proccess
        WrdNetFbProc WrdFbProc = new WrdNetFbProc(mContext);
        new Thread(WrdFbProc).start();

        //以下线程主要用来检测子设备离线状态
        new Thread() {
            @Override
            public void run() {
                DbManager db = CommonUtil.MyDbUtils();
                while (true) {
                    try {
                        if (deviceList.size() == 1) {
                            if (deviceList.get(0).getTimestamp() != timestamp) {
                                timestamp = deviceList.get(0).getTimestamp();
                            } else {
                                //ipZigbee设备离线
                                Log.d(TAG, "device offline...." + deviceList.get(0).getSerialNum());

                                String strIpZigbeeDevId = deviceList.get(0).getSerialNum();
                                try {
                                    //IpZigbee设备
                                    DeviceDb ipZigbeeDev = db.selector(DeviceDb.class).where("devId", "=", strIpZigbeeDevId).findFirst();

                                    if (ipZigbeeDev != null) {
                                        ipZigbeeDev.setStatus(Dev_STATUS_eDisconnect);        //Dev_STATUS_eDisconnect
                                        db.saveOrUpdate(ipZigbeeDev);
                                    }

                                    try {
                                        //IpZigbee子设备列表
                                        List<DeviceDb> ipZigbeeSubDevList = db.selector(DeviceDb.class).where("gwDevId", "=", strIpZigbeeDevId).findAll();
                                        if (ipZigbeeSubDevList == null || ipZigbeeSubDevList.size() == 0) {
                                            Log.d(TAG, "Nothing hardware device.");
                                            return;
                                        }

                                        for (final DeviceDb subDevice : ipZigbeeSubDevList) {
                                            //子设备设为离线
                                            subDevice.setStatus(Dev_STATUS_eDisconnect);
                                            db.saveOrUpdate(subDevice);
                                        }
                                    }catch (Exception ex){
                                        ex.printStackTrace();
                                    }
                                } catch (DbException e) {
                                    e.printStackTrace();
                                } finally {
                                    deviceList.remove(0);
                                }
                            }
                        }else if(deviceList.size() == 0) {
                            //2019/12/17, 查找数据库，上电后将有线网相关设备设置离线
                            //ipZigbee有线网相关设备上电后，默认设置为离线
                            try {
                                List<DeviceDb> listWirenetDb = db.findAll(DeviceDb.class);
                                if(listWirenetDb == null) {
                                    Log.d(TAG,"Nothing hardware device.");
                                    return;
                                }
                                for (final DeviceDb item :listWirenetDb) {
                                    if((item.getGwDevId().length() > 4)) {
                                        if (item.getGwDevId().startsWith("2011")
                                                || item.getGwDevId().startsWith("2012")
                                                || item.getGwDevId().startsWith("2010"))
                                        {
                                            if(item.getStatus() == 4) {
                                                //ipZigbee子设备设置为离线
                                                item.setStatus(Dev_STATUS_eDisconnect);
                                                db.saveOrUpdate(item);
                                                Log.d(TAG, " DeviceId : " + item.getDevId() + "offline!");
                                            }
                                        }
                                    }
                                    if((item.getDevId().length() > 4)) {
                                        if (item.getDevId().startsWith("2011")
                                                || item.getDevId().startsWith("2012")
                                                || item.getDevId().startsWith("2010"))
                                        {
                                            if(item.getStatus() == 4) {
                                                //ipZigbee设备设置为离线
                                                item.setStatus(Dev_STATUS_eDisconnect);
                                                db.saveOrUpdate(item);
                                                Log.d(TAG, " DeviceId : " + item.getDevId() + "offline!");
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        Thread.sleep(15000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        /******* Add by hy,2018/03/27 ********/
        netHandlethread = new PollTheadTemp() {

            @Override
            public void threadPoll() {
                try {
                    //ipZigbee指令发送消息队列
                    WrdNetDeContol.netSendHandle();
                    Thread.sleep(200);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };

        //启动ipZigbee指令发送的消息队列
        netHandlethread.startThread();
        /******* END! Add by hy,2018/03/27 ************/
        singleThreadExecutorReceive = Executors.newSingleThreadExecutor();
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context myContext, Intent myIntent) {
            final Intent intent = myIntent;
            final Context context = myContext;
            // TODO Auto-generated method stub
            singleThreadExecutorReceive.execute(new Runnable() {
                @Override
                public void run() {
                    if (intent.getAction().startsWith(ACTION_DEV_MANAGER, 0)) {
                        intentManageCmdProc(intent);
                    } else if (ACTION_DEV_CTL_BY_WIRED_NET.equals(intent.getAction())) {
                        //把从zigbeeservice来的广播复原
                        String currentAction = intent.getStringExtra("currentAction");
                        intent.setAction(currentAction);
                        intentControlCmdProc(intent);
                    } else if (intent.getAction().equals(ACTION_BOX_WIREDNET_IN)) {
                        Log.d(TAG, "WiredNet Join Up! *******");
                        WifiManager mWifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                        if (mWifiManager != null) {
                            mWifiManager.setWifiEnabled(false);
                            mWifiManager.setWifiEnabled(true);
                        }
                    } else if (intent.getAction().equals(ACTION_HCP_UPDATED) || intent.getAction().equals(ACTION_HCP_RESET)) {            //Add by hy,2018/03/29
                        deviceList.clear();
                        Log.d(TAG, "recive ACTION_HCP_UPDATED!");
                    }
                }
            });
        }
    };

    /**
     * 处理设备控制请求
     * @param intent
     */
    private void intentControlCmdProc(Intent intent) {
        String mac = intent.getStringExtra("macAddr");
        String deviceId = intent.getStringExtra("deviceId");
        DeviceDb me;
        DbManager db = CommonUtil.MyDbUtils();
        int netType = intent.getIntExtra("network", -1);
        Log.d(TAG, "WiredNet Device: devId: " + deviceId);    //Add by hy,2017/07/19

        try {
            me = db.selector(DeviceDb.class).where("devId", "=", deviceId).findFirst();
            if ((me == null)) {
                Log.d(TAG, "WiredNet Device: Not found, devId:" + deviceId);
                return;
            } else {
                Log.d(TAG, "WiredNet Device:  found DevId:" + deviceId);
                if ((me.getNetType() != DeviceManager.ETHERNET_NETWORK) && me.getGwDevId().length() < 1) {
                    Log.d(TAG, "WiredNet Device: invalid ethGw devId:" + deviceId + " gwDevid" + me.getGwDevId());
                    return;
                } else {
                    Log.d(TAG, "netType2: " + netType + "normal:" + me.getNetType() + " gwDevid" + me.getGwDevId());
                }
            }

            if (netType == DeviceManager.KNX_NETWORK) {  //Modify by hy,
                Log.d(TAG, "WiredNet Device: Not found, devId:" + deviceId);
            }

            Log.d(TAG, "WiredNet Service ACTION_DEV_CTL DevId:" + deviceId);

            switch (intent.getAction()) {
                case ACTION_CTL_LIGHT: {
                    //控制灯光
                    int sw = intent.getIntExtra("sw", -1);
                    int brightness = intent.getIntExtra("brightness", -1);
                    int color = 0;
                    int channel;
                    int iDevid;

                    if (deviceId.length() > 12) {
                        iDevid = Integer.parseInt(deviceId.substring(13, 16), 10);
                        channel = iDevid%10;
                        if (channel>=8 || sw > 1) {
                            Log.d(TAG, "light8 channel error:" + channel + "  iDevid:" + iDevid + " sw:" + sw);
                            return ;
                        }
                        color = channel;
                    }

                    if (sw == 0)
                        brightness = 0;
                    else {
                        if (brightness == -1)
                            brightness = 0;
                    }
                    me.setSw(sw);
                    me.setBrightness(brightness);
                    me.setColor(color);

                    if (debug) Log.d(TAG, "ACTION_CTL_LIGHT");
                    if (debug)
                        Log.d(TAG, "MAC:" + mac + ",sw:" + sw + ",brightness:" + brightness + ",color:" + color);

                    break;
                }
                case ACTION_CTL_LIGHT_8:{
                    //控制一拖8灯
                    //Log.e(TAG,"============ACTION_CTL_LIGHT_8======");
                    int sw1 = intent.getIntExtra("sw1", -1);
                    int sw2 = intent.getIntExtra("sw2", -1);
                    int sw3 = intent.getIntExtra("sw3", -1);
                    int sw4 = intent.getIntExtra("sw4", -1);
                    int sw5 = intent.getIntExtra("sw5", -1);
                    int sw6 = intent.getIntExtra("sw6", -1);
                    int sw7 = intent.getIntExtra("sw7", -1);
                    int sw8 = intent.getIntExtra("sw8", -1);
                    int temp = 0;
                    int channel = 0;
                    DeviceDb subDevDb;
                    StringBuilder subDeviceId = new StringBuilder();
                    subDeviceId.append("1030");
                    subDeviceId.append(deviceId.substring(4,12));
                    subDeviceId.append("0000");

                    if (sw1 >= 0) {
                        temp += (sw1*(1<<0));
                        channel += (1<<0);
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw1 != subDevDb.getSw()) {
                            subDevDb.setSw(sw1);
                            db.saveOrUpdate(subDevDb);
                            Log.d(TAG, "devid:" + subDeviceId.toString() + " sw:" + sw1);
                        }
                    }
                    if (sw2 >= 0) {
                        temp += (sw2*(1<<1));
                        channel += (1<<1);
                        subDeviceId.setCharAt(15, '1');
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw2 != subDevDb.getSw()) {
                            subDevDb.setSw(sw2);
                            db.saveOrUpdate(subDevDb);
                            Log.d(TAG, "devid:" + subDeviceId.toString() + " sw:" + sw2);
                        }
                    }
                    if (sw3 >= 0) {
                        temp += (sw3*(1<<2));
                        channel += (1<<2);
                        subDeviceId.deleteCharAt(15);
                        subDeviceId.replace(15,15,"2");
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw3 != subDevDb.getSw()) {
                            subDevDb.setSw(sw3);
                            db.saveOrUpdate(subDevDb);
                            Log.d(TAG, "devid:" + subDeviceId.toString() + " sw:" + sw3);
                        }
                    }
                    if (sw4 >= 0) {
                        temp += (sw4*(1<<3));
                        channel += (1<<3);
                        subDeviceId.deleteCharAt(15);
                        subDeviceId.replace(15,15,"3");
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw4 != subDevDb.getSw())
                        {
                            subDevDb.setSw(sw4);
                            db.saveOrUpdate(subDevDb);
                            Log.d(TAG, "devid:" + subDeviceId.toString() + " sw:" + sw4);
                        }
                    }
                    if (sw5 >= 0) {
                        temp += (sw5*(1<<4));
                        channel += (1<<4);
                        subDeviceId.deleteCharAt(15);
                        subDeviceId.replace(15,15,"4");
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw5 != subDevDb.getSw()) {
                            subDevDb.setSw(sw5);
                            db.saveOrUpdate(subDevDb);
                            Log.d(TAG, "devid:" + subDeviceId.toString() + " sw:" + sw5);
                        }
                    }
                    if (sw6 >= 0) {
                        temp += (sw6*(1<<5));
                        channel += (1<<5);
                        subDeviceId.deleteCharAt(15);
                        subDeviceId.replace(15,15,"5");
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw6 != subDevDb.getSw()) {
                            subDevDb.setSw(sw6);
                            db.saveOrUpdate(subDevDb);
                            Log.d(TAG, "devid:" + subDeviceId.toString() + " sw:" + sw6);
                        }
                    }
                    if (sw7 >= 0) {
                        temp += (sw7*(1<<6));
                        channel += (1<<6);
                        subDeviceId.deleteCharAt(15);
                        subDeviceId.replace(15,15,"6");
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw7 != subDevDb.getSw()) {
                            subDevDb.setSw(sw7);
                            db.saveOrUpdate(subDevDb);
                            Log.d(TAG, "devid:" + subDeviceId.toString() + " sw:" + sw7);
                        }
                    }
                    if (sw8 >= 0) {
                        temp += (sw8*(1<<7));
                        channel += (1<<7);
                        subDeviceId.deleteCharAt(15);
                        subDeviceId.replace(15,15,"7");
                        subDevDb = db.selector(DeviceDb.class).where("devId", "=", subDeviceId.toString()).findFirst();
                        if(subDevDb!= null && sw8 != subDevDb.getSw()) {
                            subDevDb.setSw(sw8);
                            db.saveOrUpdate(subDevDb);
                            Log.d(TAG, "devid:" + subDeviceId.toString() + " sw:" + sw8);
                        }
                    }
                    if (channel > 0) {
                        channel += (1<<15);//set 1to8 scene flag to mcu
                    }
                    me.setSw(temp);
                    me.setColor(channel);
                    Log.d(TAG, "devid:" + deviceId + "temp:" + temp + "channel" + channel);
                    Log.e(TAG,"========ACTION_CTL_LIGHT_8======");
                }
                break;
                case ACTION_CTL_AIRCONDITION:
                case ACTION_CTL_FLOOR_HEATING: {
                    //控制空调、地暖
                    if (debug) Log.d(TAG, "ACTION_CTL_AIRCONDITION or ACTION_CTL_FLOOR_HEATING ");
                    int sw = intent.getIntExtra("sw", me.getSw());
                    int mode = intent.getIntExtra("mode", me.getMode());
                    int temp = intent.getIntExtra("temperature", me.getSetTemp());
                    int wind = intent.getIntExtra("wind", me.getWind());

                    me.setSw(sw);
                    me.setMode(mode);
                    me.setSetTemp(temp);
                    me.setWind(wind);
                    Log.i(TAG, "sw" + sw + "temp:" + temp + ",wind:" + wind + ",mode:" + mode);
                    break;
                }
                case ACTION_CTL_CURTAIN:
                    //控制窗帘
                    if (debug) Log.d(TAG, "ACTION_CTL_CURTAIN");
                    int runstate = intent.getIntExtra("runstate", -1);
                    int runstate2 = intent.getIntExtra("runstate2", -1);

                    if(runstate !=-1){
                        me.setCurtainState(runstate);
                    }

                    if(runstate2 !=-1){
                        me.setCurtainState2(runstate2);
                    }

                    break;
                case ACTION_CTL_FRESHAIR: {
                    //控制新风
                    if (debug) Log.d(TAG, "ACTION_CTL_FRESHAIR");
                    int sw = intent.getIntExtra("sw", me.getSw());
                    int wind = intent.getIntExtra("wind", me.getWind());
                    int mode = intent.getIntExtra("mode", me.getMode());        //Add by hy,2017/07/19
                    int sw2 = intent.getIntExtra("sw2", me.getCurtainState());    //

                    if (me.getSw() == sw && me.getWind() == wind && me.getMode() == mode) {  //Add by hy,2017/07/20
                        sw2 |= 0x80;
                    } else {
                        sw2 &= 0x7f;
                    }

                    me.setSw(sw);
                    me.setWind(wind);
                    me.setMode(mode);
                    me.setCurtainState(sw2);
                    Log.i(TAG, "sw " + sw + ",wind: " + wind + ",mode: " + mode + ",sw2: " + sw2);
                    break;
                }
                case ACTION_CTL_SWITCH:
                    break;
                case ACTION_CTL_TRANSDATA:
                    break;
            }
            Log.i(TAG, "CTL Name:" + me.getName());
            me.setRetryCnt(0);
            db.saveOrUpdate(me);
            deviceControl(intent, me, deviceId);
        } catch (DbException | NumberFormatException e) {
            e.printStackTrace();
            intentRsp(intent.getAction(), 1);
        }
    }

    /**
     * 处理管理类指令
     * @param intent
     */
    private void intentManageCmdProc(Intent intent) {
        int type = intent.getIntExtra("type", 0);
        int netType = intent.getIntExtra("network", 0);
        String deviceId = intent.getStringExtra("deviceId");
        String mac = intent.getStringExtra("macAddr");
        String gwDevId = intent.getStringExtra("gwDevId");
        int autoFlag = intent.getIntExtra("auto", 0);

        if (netType != DeviceManager.ETHERNET_NETWORK) {
            Log.d(TAG, "NetWorkType error: network type is " + netType);
            return;
        }
        Log.d(TAG, "WrdNet Service Manager:" + intent.getAction());

        /********** BEGIN: Add by hy,2017/09/08 ************/
        DbManager db = CommonUtil.MyDbUtils();
        try {
            DeviceDb me = db.selector(DeviceDb.class).where("gwDevId", "=", gwDevId).findFirst();
            if (me == null) {
                Log.d(TAG, "WiredNet Device: Not found, gwDevId:" + gwDevId/*deviceId*/);
                return;
            }

            switch (intent.getAction()) {
                case ACTION_DEV_ADD:
                    //设备添加
                    Log.d(TAG, "==ACTION_DEV_ADD====/设备添加!");
                    if (!CommonUtil.checkMacFormat(mac)) {
                        Log.d(TAG, "WireNet ACTION_DEV_ADD mac error!");
                        return;
                    }

                    if (type != 0)    //Add by hy,2017/09/12 Test
                        deviceId = type + deviceId;

                    if (autoFlag != 0) {
                        try {
                            List<Navigation> navigationList = db.findAll(Navigation.class);
                            if (navigationList != null) {
                                for (final Navigation item : navigationList) {
                                    if (item.getDevId().equals(deviceId)) {
                                        item.setType(type);
                                        db.saveOrUpdate(item);
                                        autoFlag = 0;
                                        break;
                                    }
                                }
                            }

                            if (autoFlag != 0) {
                                NavigationDao dao3 = new NavigationDao(this);
                                Navigation nav = new Navigation();
                                nav.setDevId(deviceId);
                                nav.setType(type);
                                dao3.add(nav);
                                Log.d(TAG, "ACTION_DEV_ADD,WiredNet NavigationDao");
                            }
                        } catch (DbException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    if (debug) Log.d(TAG, "ACTION_DEV_ADD,WiredNet");

                    if (gwDevId == null)
                        gwDevId = "";

                    deviceManager(intent, gwDevId, deviceId, "add", mac, null, null);    //Add by hy,2017/09/12
                    break;
                case ACTION_DEV_REMOVE:
                    //设备移除
                    mDeviceDbManager.del(mac);
                    if (debug) Log.d(TAG, "ACTION_DEV_REMOVE");
                    break;
                /********************* Add by hy,2017/09/08 Zigbee gateway device manager **********************/
                case ACTION_DEV_BIND:
                    //设备绑定
                    String bindDevId = intent.getStringExtra("bindDevId");
                    int group = intent.getIntExtra("group", 0);
                    int config = intent.getIntExtra("config", 0);
                    String param = config + "and" + group;                //Add by hy,2019/03/12, Swap config and group

                    Log.d(TAG, "ACTION_DEV_BIND success :" + "mac: " + mac + " BindDevId: " + bindDevId);

                    if (!CommonUtil.checkMacFormat(mac)) {
                        Log.e(TAG, "ACTION_DEV_BIND mac error :");
                        return;
                    }

                    deviceManager(intent, gwDevId, deviceId, "bind", mac, bindDevId, param);
                    intentRsp(ACTION_DEV_BIND, 0);
                    break;
                case ACTION_DEV_SECURITYKEY:
                    String key = intent.getStringExtra("key");
                    Log.d(TAG, "ACTION_DEV_SecurityKey success :" + "key:" + key);

                    if (!CommonUtil.checkMacFormat(key)) {
                        Log.e(TAG, "ACTION_DEV_SecurityKey key length error :");
                        return;
                    }
                    deviceManager(intent, gwDevId, deviceId, "set_key", null, null, key);
                    intentRsp(ACTION_DEV_SECURITYKEY, 0);
                    break;
                case ACTION_DEV_STATUS:
                    //设备状态
                    Log.d(TAG, "ACTION_DEV_STATUS success, mac :" + mac);
                    deviceManager(intent, gwDevId, deviceId, "status", mac, null, null);
                    intentRsp(ACTION_DEV_STATUS, 0);
                    break;
                /**************** END! Add by hy,2017/09/08 *****************/
                default:
                    intentRsp(ACTION_DEV_CLEARLIST, 1);
                    Log.e(TAG, "Error:");
                    break;
            }

            Log.e(TAG, "reutrn success :");

        } catch (DbException | NumberFormatException e) {
            e.printStackTrace();
            intentRsp(intent.getAction(), 1);
        }
    }

    private void intentRsp(String intent, int result) {
        Intent mIntent = new Intent(ACTION_INFO_RETURN);
        mIntent.putExtra("intentId", intent);
        mIntent.putExtra("return", result);
        mContext.sendBroadcast(mIntent);
    }

    /**
     * 设备控制
     * @param intent
     * @param me
     * @param deviceID
     */
    private void deviceControl(Intent intent, DeviceDb me, String deviceID) {
        int size = deviceList.size();
        String device_ip;

        if (size == 0) {
            Log.d(TAG, "device list is null!");
            intentRsp(intent.getAction(), 1);
            return;
        }

        DeviceDb gwDev = DeviceDao.getInstance().getDeviceDb(me.getGwDevId());
        if (gwDev == null) {
            Log.d(TAG, "this dev has no gwDev" + gwDev);
        }

        for (int i = 0; i < size; i++) {
            String gwOrDevId = deviceList.get(i).getSerialNum();
            if (gwOrDevId.equals(deviceID)
                    || me.getGwDevId().equals(gwOrDevId)
                    || (gwDev!=null && gwDev.getGwDevId().equals(gwOrDevId)))    //
            {

                device_ip = deviceList.get(i).getIp();
                //有线网设备控制
                WrdNetDeContol.wireNetPacketAndControl(intent, me, gwDev, device_ip);
                com.wholeintech.utils.LogUtils.d(TAG,"====deviceControl==intent:"+intent.toUri(0));
                Log.d(TAG, "deviceControl===intent:" +intent+"gwDev:"+gwDev+"==device_ip:"+device_ip);
                //发送状态改变广播到上层
                CommonUtil.sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,me.getBoxId(),me.getDevId(),me.getType(),false,null);
                Log.e(TAG,"sendBroadcastMsg===4");
                break;
            }

            if (i == size - 1) {
                Log.d(TAG, "device is not in the list!");
                intentRsp(intent.getAction(), 1);
            }
        }
    }

    //Add by hy,2017/09/08
    private void deviceManager(Intent intent, String gwDevId, String deviceId, String cmd, String mac1, String bindDevId, String key) {
        int size = deviceList.size();
        String device_ip;

        if (size == 0) {
            Log.d(TAG, "device list is null!");
            intentRsp(intent.getAction(), 1);
            return;
        }

        for (int i = 0; i < size; i++) {
            String gwOrDevId = deviceList.get(i).getSerialNum();
            if (gwDevId.equals(gwOrDevId))    //only gateway existing equipment management
            {
                device_ip = deviceList.get(i).getIp();
                WrdNetDeContol.netSendBufferCread(device_ip, cmd, mac1, bindDevId, deviceId, key);                //Add by hy,2018/03/27
                break;
            }

            if (i == size - 1) {
                Log.d(TAG, "device is not in the list!" + "gwDevId: " + gwDevId + "deviceId: " + deviceId);
                intentRsp(intent.getAction(), 1);
            }
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public void onDestroy() {
        super.onDestroy();
        singleThreadExecutorReceive.shutdown();
        unregisterReceiver(mReceiver);
        CommonUtil.MyDbUtilsClose();
    }

}
